package com.example.rabbitspringamqp.controller;

import com.example.rabbitspringamqp.config.RabbitMQConfig;
import com.example.rabbitspringamqp.dto.OrderDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author haitao
 * @date 2021/8/19 4:49 下午
 */
@RestController
public class MessageController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/test")
    public String sendDirectMessage() throws JsonProcessingException {

        OrderDTO dto =new OrderDTO();
        dto.setId(1);
        dto.setName("飞天茅台");
        dto.setContent("喝了直接飞上天");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(dto);

        Message message = MessageBuilder.withBody(jsonStr.getBytes(StandardCharsets.UTF_8))
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("UTF-8")
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .build();

        for (int i = 0; i < 10; i++) {
            rabbitTemplate.send(RabbitMQConfig.DIRECT_EXCHANGE,"direct",message);
        }
        return "success";
    }
}
